package com.cuckoo.mall.thus.menucart;


import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.base.BaseListFragment;
import com.bgn.baseframe.utils.BaseStringUtil;
import com.bgn.baseframe.utils.KeyboardHelper;
import com.bgn.baseframe.utils.ToastUtil;
import com.bgn.baseframe.utils.UiUtil;
import com.bgn.baseframe.utils.decoration.CommonDecoration;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cuckoo.mall.R;
import com.cuckoo.mall.javabean.CartProductItem;
import com.cuckoo.mall.thus.manager.UserInfoManager;
import com.cuckoo.mall.thus.start.MainActivity;
import com.cuckoo.mall.thus.utils.DialogHelper;
import com.cuckoo.mall.thus.utils.UpdateNumDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.bgn.baseframe.base.BaseActivity.DATASTRING;
import static com.bgn.baseframe.base.BaseActivity.ID;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class MenucartFragment extends BaseListFragment<MenucartContract.View, MenucartPresenter, CartProductItem> implements MenucartContract.View {
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.check_state)
    CheckBox checkState;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_del)
    TextView tvDel;
    @BindView(R.id.tv_back)
    TextView tvBack;

    @BindView(R.id.swipe_view)
    SwipeRefreshLayout swipeView;
    @BindView(R.id.tv_go_shiping)
    TextView tvGoShiping;
    @BindView(R.id.lly_no_data)
    LinearLayout llyNoData;
    @BindView(R.id.tv_loading)
    TextView tvLoading;
    @BindView(R.id.rly_root)
    RelativeLayout rlyRoot;
    /*状态变量*/
    private boolean shouldReFresh = false;
    private boolean isEditMode = false;


    @Override
    protected boolean shoudOpenLoadMore() {
        return false;
    }

    @Override
    protected int getLaoutResouse() {
        return R.layout.fragment_cart;
    }

    @Override
    protected void initOtherUi(View rootView) {
        ButterKnife.bind(this, rootView);
        checkState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (datas != null && datas.size() > 0) {
                    for (CartProductItem item : datas) {
                        item.setCheckd(checkState.isChecked());
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    /*初始化数据适配器*/
    @Override
    protected BaseQuickAdapter setAdapter() {
        adapter = new CartQiuckAdapter(datas, new CartQiuckAdapter.ItemCheckChange() {
            @Override
            public void whenItemCheckChangeCllBack() {
                resetBootmViewData();
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (datas.get(position).getProduct_info() != null)
                    ARouter.getInstance().build("/mall/goodMultipleDetailActivity").withString(ID, datas.get(position).getProduct_info().getProduct_id()).navigation();
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                final int oldNum;
                switch (view.getId()) {
                    case R.id.et_counts:
                        String oldText = ((TextView) view).getText().toString();
                        oldNum = Integer.parseInt(oldText);
                        new UpdateNumDialog(getActivity(), oldText, new UpdateNumDialog.OnClickOkLister() {
                            @Override
                            public void onOK(String newNum) {
                                updateCartItemsNum(position, oldNum, Integer.parseInt(newNum), datas.get(position).getCart_id());
                            }
                        }).show();
                        UiUtil.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                KeyboardHelper.showKeyboard();
                            }
                        }, 150);
                        break;
                    case R.id.iv_add:
                        oldNum = datas.get(position).getNumber();
                        updateCartItemsNum(position, oldNum, oldNum + 1, datas.get(position).getCart_id());
                        break;
                    case R.id.iv_minus:
                        oldNum = datas.get(position).getNumber();
                        updateCartItemsNum(position, oldNum, oldNum - 1, datas.get(position).getCart_id());
                        break;
                }
            }
        });
        return adapter;
    }

    /*设置MANAGE*/
    @Override
    protected void setLayoutManage() {
        recycleView.addItemDecoration(new CommonDecoration(10));
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

    /******点击处理****/
    @OnClick({R.id.tv_back, R.id.tv_edit, R.id.tv_buy, R.id.tv_del, R.id.tv_go_shiping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                getActivity().finish();
                break;
            case R.id.tv_edit:
                swichMode();
                break;
            case R.id.tv_buy:

                toAddOrder();
                break;
            case R.id.tv_del:
                deletCartItems();
                break;
            case R.id.tv_go_shiping:

                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).goHomePage();
                } else {
                    ARouter.getInstance().build("/mall/mainActivity").withString("action", "home").navigation();
                }
                break;
        }
    }


    /****************网络请求与回调********************/
    @Override
    protected void onRefreshData() {
        if (isNetworkerConnectHint()) {
            showLoadingView();
            mPresenter.refreshList();
        } else {
            showDefaultView();
        }
        swipeView.setRefreshing(false);
    }

    @Override
    protected void initListData() {
        if (isNetworkerConnectHint()) {
            datas.clear();
            mPresenter.loadCartList();
        } else {
            showDefaultView();
        }
    }

    @Override
    protected void loadMoreData() {

    }

    /*回调*/
    @Override
    public void whenGetCartDatas(List<CartProductItem> datas, int type) {
        llyNoData.setVisibility(View.GONE);
        tvEdit.setVisibility(View.VISIBLE);
        handleData(datas, type);
        //  setBottomViewData();
        // setTopView();
    }

    @Override
    public void whenCartNoData() {
        datas.clear();
        adapter.notifyDataSetChanged();
        llyNoData.setVisibility(View.VISIBLE);
        tvEdit.setVisibility(View.GONE);
    }

    @Override
    public void whenUpdateNumFaild(int position, int oldNum) {
        datas.get(position).setNumber(oldNum);
        adapter.notifyDataSetChanged();

        rlyRoot.requestFocus();
        KeyboardHelper.hideKeyboard(rlyRoot);
    }

    @Override
    public void whenUpdateSucceed(int position, int newNum) {
        datas.get(position).setNumber(newNum);
        adapter.notifyDataSetChanged();
        // setBottomViewData();
        resetBootmViewData();
        rlyRoot.requestFocus();
        KeyboardHelper.hideKeyboard(rlyRoot);

    }

    @Override
    public void whenDeleteSucceed(List<Integer> positions) {
        ToastUtil.showInfo(getString(R.string.delete_success));
        for (int i = positions.size() - 1; i >= 0; i--) {
            adapter.remove(positions.get(i));
        }
        if (datas == null || datas.size() == 0) {
            llyNoData.setVisibility(View.VISIBLE);
            tvEdit.setVisibility(View.GONE);
        }
        resetBootmViewData();
        //setBottomViewData();
    }

    /******改变购物车数量****/
    public void updateCartItemsNum(int position, int oldNum, int cart_num, String cart_id) {
        if (isNetworkerConnectHint() && cart_num > 0 && cart_num <= 200) {
            KeyboardHelper.hideKeyboard(rlyRoot);
            rlyRoot.requestFocus();
            showLoadingView();
            mPresenter.updateCartItemsNum(position, oldNum, cart_num, cart_id);
        }
    }

    /******删除购物车商品****/
    public void deletCartItems() {
        if (isEditMode && isNetworkerConnectHint()) {
            String ids = getCartIdStrings();
            if (TextUtils.isEmpty(ids)) {
                ToastUtil.showInfo(getString(R.string.please_select_del_product));
            } else {
                DialogHelper.showConfirmDialog(getActivity(), getString(R.string.sure_to_delete_product), getString(R.string.delete), getString(R.string.cancel), new DialogHelper.DialogPressCallBack() {
                    @Override
                    public void whenPressRightButton() {
                        showLoadingView();
                        mPresenter.deleteCartItem(getSelectedPositions(), getCartIdStrings());
                    }
                });
            }
        }
    }

    /******去下单****/
    public void toAddOrder() {
        if (!isEditMode && isNetworkerConnectHint()) {
            String dataString = getSelectedItemString();
            if (TextUtils.isEmpty(dataString)) {
                ToastUtil.showInfo(getString(R.string.please_select_buy_product));
            } else {
                ARouter.getInstance().build("/mall/addOrderFromCartActivity").withString(DATASTRING, dataString).navigation();
            }
        }
    }

    /*******************控制未登录和刷新购物车时机和软件盘体验*********************/
    public void resetFreshState(boolean state) {
        shouldReFresh = state;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserInfoManager.getInstance().isLogin()) {
            if (shouldReFresh) {
                shouldReFresh = false;
                onRefreshData();
            }
        } else {
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).goHomePage();
            } else {
                ARouter.getInstance().build("/mall/mainActivity").navigation();
            }
        }
    }

    @Override
    public void onStop() {
        KeyboardHelper.hideKeyboard(rootView);
        super.onStop();
    }

    /*********重置底部View的数据******/
    private void resetBootmViewData() {
        int totalPrice = 0;
        boolean isAllChecked = true;
        for (CartProductItem item : datas) {
            if (item.isCheckd()) {
                if (item.getProduct_info() != null) {
                    totalPrice += item.getNumber() * item.getProduct_info().getPrice();
                }
            } else {
                isAllChecked = false;
            }

        }
        if (datas != null && datas.size() > 0) {
            checkState.setChecked(isAllChecked);
            if (totalPrice == 0) {
                tvPrice.setText("");
            } else {
                tvPrice.setText(datas.get(0).getProduct_info().getCurrency() + " " + BaseStringUtil.getPrioceFormatString(totalPrice));
            }

        } else {
            checkState.setChecked(false);
            tvPrice.setText("");
        }

    }

    /*******************切换模式*********************/
    private void swichMode() {
        if (isEditMode) {
            isEditMode = false;
            tvEdit.setText(getString(R.string.edit));
            tvBuy.setVisibility(View.VISIBLE);
            tvPrice.setVisibility(View.VISIBLE);
            tvDel.setVisibility(View.GONE);
        } else {
            isEditMode = true;
            tvEdit.setText(getString(R.string.complit));
            tvBuy.setVisibility(View.GONE);
            tvPrice.setVisibility(View.GONE);
            tvDel.setVisibility(View.VISIBLE);
        }
        for (CartProductItem item : datas) {
            item.setCheckd(false);
        }
        ((CartQiuckAdapter) adapter).changeMode(isEditMode);
    }

    /*******************获取选择的位置数组*********************/
    private List<Integer> getSelectedPositions() {
        List<Integer> selects = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).isCheckd()) {
                selects.add(i);
            }
        }
        return selects;
    }

    /*******************获取选择的位置对应的ID数组*********************/
    private String getCartIdStrings() {
        String idsString = "";
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).isCheckd()) {
                idsString = idsString + datas.get(i).getCart_id() + ",";
            }
        }
        if (!TextUtils.isEmpty(idsString)) {
            idsString = idsString.substring(0, idsString.length() - 1);
        }
        return idsString;
    }

    /*******************获取选择的位置对应的数据json*********************/
    private String getSelectedItemString() {
        List<CartProductItem> selectedItem = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).isCheckd()) {
                selectedItem.add(datas.get(i));
            }
        }
        if (selectedItem.size() > 0) {
            return GsonUtil.toJson(selectedItem);
        } else {
            return "";
        }
    }

    public void showBackIco() {
        tvBack.setVisibility(View.VISIBLE);
    }
}
